import apiService from '@/services/api'
// import {userInfo} from "node:os";
import { CozeAPI } from '@coze/api';

export default {
  name: 'Translation',
  data() {
    return {
      // 通知系统
      notifications: [],
      notificationId: 0,

      // 分类数据
      categories: [
        { id: 3, uid:6, name: '专长' },
        { id: 4, uid:25, name: '种族职业/基本属性' },
        { id: 7, uid:7, name: '天赋/R天赋' },
        { id: 5, uid:5, name: '法术' },
        { id: 9, uid:23, name: '技能' },
        { id: 8, uid:11, name: '天命' },
        { id: 81, uid:18, name: '   -天命(DDS)' },
        { id: 82, uid:36, name: '   -天命(鲨鱼)' },
        { id: 11, uid:9, name: '副本'},
        { id: 6, uid:28, name: '其它界面' },
        { id: 83, uid:39, name: '   -其他(六指)' },
        { id: 84, uid:3, name: '   -其他(Vivn)' },
        { id: 85, uid:17, name: '   -其他(Paios)' },
        { id: 86, uid:2, name: '   -其他(国服版本)' },
        { id: 87, uid:49, name: '   -其他(AI)' },
        { id: 10, uid:47, name: '审核版本' },
      ],
      //审核ID
      audit_id: 47,
      selectedCategory: 1,

      // 搜索和排序
      searchQuery: '',
      sortField: 'file_id',
      sortOrder: 'asc',
      filter_translated: 'N/A',
      // 翻译者
      commit_user_id: -1,

      // 翻译条目数据
      items: [],
      //分页
      pagination: {
        has_next: false,
        has_prev: false,
        page: 1,
        pages: 0,
        per_page: 5,
        total: 0
      },
      showTranslationModal: false,
      currentTranslations: [],
      modalTitle: '',
      tooltipPosition: {
        top: 0,
        left: 0
      },
      allowCopy: false,
      currentItem: null,
      gossip_id: '',
      file_id: '',
    }
  },
  computed: {},
  methods: {
    // userInfo,
    // 格式化时间显示
    formatDateTime(dateTime) {
      if (!dateTime) return '未知';
      try {
        const date = new Date(dateTime);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        console.error('时间格式化失败:', error);
        return '未知';
      }
    },
    //uid: -1:清空；0：我翻译的；其它大于0：指定用户ID
    setUID(category, uid) {
      this.selectedCategory = category;
      if (uid == -1) {
        this.commit_user_id = -1;
      } else if (uid == 0) {
        const currentUser = this.getCurrentUserInfo();
        if (!currentUser || !currentUser.user_id) {
          console.warn('未找到当前登录用户信息');
          return null;
        }
        this.commit_user_id = currentUser.user_id;
      } else {
        this.commit_user_id = uid;
      }
      this.fetchTranslations();
    },
    showTranslationList(translations, event, item) {
      console.log(item);
      this.currentItem = item;
      if (translations && translations.length > 0) {
        this.currentTranslations = translations;
        this.modalTitle = `翻译列表 (${translations.length} 个翻译)`;
        this.showTranslationModal = true;

        // 计算弹窗位置
        const rect = event.target.getBoundingClientRect();
        this.tooltipPosition = {
          top: rect.bottom + window.scrollY + 5,
          left: rect.left + window.scrollX
        };
      }
    },
    closeTranslationModal() {
      this.showTranslationModal = false;
      this.currentTranslations = [];
    },
    requireRole(level) {
      const currentUser = this.getCurrentUserInfo();
      if (!currentUser || !currentUser.user_id) {
        console.warn('未找到当前登录用户信息');
        return null;
      }
      return currentUser.role && currentUser.role > level
    },
    // 获取当前登录用户信息
    getCurrentUserInfo() {
      const loginInfo = localStorage.getItem('loginInfo');
      if (loginInfo) {
        try {
          return JSON.parse(loginInfo);
        } catch (e) {
          console.error('解析登录信息失败:', e);
          return null;
        }
      }
      return null;
    },
    getTranslationText(translations) {
      // 根据translations数组计算textarea的内容
      if (!translations || translations.length === 0) return '';

      let findUID = 0;
      if (this.allowEdit()) {//编辑模式
        // 获取当前登录用户信息
        const currentUser = this.getCurrentUserInfo();
        if (!currentUser || !currentUser.user_id) {
          console.warn('未找到当前登录用户信息');
          return null;
        }
        findUID = currentUser.user_id;
      }else{
        findUID = this.commit_user_id;
      }
      
      // 在items中查找commit_user等于当前user_id的第一条记录
      const firstTranslation = translations.find(item => {
        return item.commit_user && item.commit_user === findUID;
      });
      // 示例：返回第一个翻译或合并所有翻译
      return { chinese: firstTranslation?.content || '', remark: firstTranslation?.remark || '' };
    },
    allowEdit() {
      return this.selectedCategory <= 2;
    },
    copyTranslation(translation) {
      console.log(translation);
      if (translation.content ) {
        if(this.currentItem != null){
          this.items.forEach(item => {
            if(item.file_id == this.currentItem.file_id && item.gossip_id == this.currentItem.gossip_id){
              item.chinese = translation.content.substring(1, translation.content.length - 1);
            }
          });
        }

        this.showTranslationModal = false;
      }
    },
    checkValueNoChange(item) {
      if(item.chinese == undefined){
        item.chinese = '';
      }
      if (item.translate_prev == undefined){
        item.translate_prev = '';
      }
      return item.chinese === item.translate_prev;
    },
    // 从服务器获取翻译数据
    async fetchTranslations() {
      this.closeTranslationModal();
      this.items = [];
      // 将 pagination 和 searchQuery 作为参数传递给 API
      let pageNum = 5;
      if (!this.allowEdit()||this.selectedCategory == 2) {
        this.fetchUserHistory();
        return;
        pageNum = 20;
      }
      const params = {
        page: this.pagination.page,
        per_page: pageNum,
        search: this.searchQuery,
        sort_field: this.sortField,
        sort_order: this.sortOrder,
        is_translated: this.filter_translated,
        commit_user_id: this.commit_user_id,
        file_id: this.file_id,
        gossip_id: this.gossip_id,
      };
      try {
        // 模拟API调用，实际项目中应替换为真实的API端点
        const response = await apiService.todo(params);
        if (response.success) {
          this.items = response.data.data;
          // 初始化每个 item 的 chinese 字段
          this.items.forEach(item => {
            item.content = item.content.substring(1, item.content.length - 1);//显示时去掉首尾中括号
            item.translate_prev = '';
            if (!item.chinese) {
              const translation = this.getTranslationText(item.translations)
              if (translation.chinese) {
                item.chinese = translation.chinese;

                if (item.chinese.substring(0, 1) == '[') {
                  item.chinese = item.chinese.substring(1, item.chinese.length);//显示时去掉前置中括号
                }
                if (item.chinese.substring(item.chinese.length - 1) == ']') {
                  item.chinese = item.chinese.substring(0, item.chinese.length - 1);//显示时去掉后置中括号
                }
              } else {
                item.chinese = translation.content;
              }
              item.remark = translation.remark;
            } else {
              if (item.chinese.substring(0, 1) == '[') {
                item.chinese = item.chinese.substring(1, item.chinese.length);//显示时去掉前置中括号
              }
              if (item.chinese.substring(item.chinese.length - 1) == ']') {
                item.chinese = item.chinese.substring(0, item.chinese.length - 1);//显示时去掉后置中括号
              }
            }

            item.translations.forEach(trans => {
               if(trans.commit_user == this.audit_id){
                 item.mention = '此条目已审核过了，如确定要修改请告知审核人';
               }
            });

            item.translate_prev = item.chinese;//用于保存按钮的禁用启用
          });
          if (response.data.pagination) {
            this.pagination = response.data.pagination;
          } else {
            console.warn('Pagination data is missing in response');
          }
        }
      } catch (error) {
        console.error('获取翻译数据失败:', error);
        this.error = '获取数据失败，请稍后重试';
        this.addNotification('error', '获取数据失败', '无法从服务器获取翻译数据');
      }
    },

    async fetchUserHistory() {
      let pageNum = 20;
      const params = {
        page: this.pagination.page,
        per_page: pageNum,
        search: this.searchQuery,
        sort_field: this.sortField,
        sort_order: this.sortOrder,
        is_translated: this.filter_translated,
        commit_users: this.commit_user_id,
        file_id: this.file_id,
        gossip_id: this.gossip_id,
      };
      try {
        // 模拟API调用，实际项目中应替换为真实的API端点
        const response = await apiService.user_trans_history(params);
        if (response.success) {
          this.items = response.data.data;
          // 初始化每个 item 的 chinese 字段
          this.items.forEach(item => {
            item.chinese = item.content.substring(1, item.content.length - 1);//显示时去掉首尾中括号
            item.content = item.English.substring(1, item.English.length - 1);//显示时去掉首尾中括号
            item.updated_at = item.updated_at.substring(0, 19).replace('T', ' ');//显示时去掉毫秒
            item.last_audit_at = '';
            item.audited = false;
            item.audited_content = '';
            item.translations = item.history;
            if (item.commit_user == this.audit_id) {
              item.audited = true;
              item.audited_content = item.chinese;
            }else if (item.history && this.getCurrentUserInfo().user_id == this.audit_id && item.commit_user != this.audit_id) {
              
              item.history.forEach(trans => {
                console.log(trans.commit_user, this.audit_id);
                if(trans.commit_user == this.audit_id){
                  console.log(trans.updated_at, item.updated_at);
                  item.last_audit_at = trans.updated_at.substring(0, 19).replace('T', ' ');//显示时去掉毫秒
                  if (item.last_audit_at >= item.updated_at) {
                    item.audited = true;
                    item.audited_content = trans.content.substring(1, trans.content.length - 1);//显示时去掉首尾中括号
                  }
                  return;
                }
              });
            }
          });
          if (response.data.pagination) {
            this.pagination = response.data.pagination;
          } else {
            console.warn('Pagination data is missing in response');
          }
        }
      } catch (error) {
        console.error('获取翻译数据失败:', error);
        this.error = '获取数据失败，请稍后重试';
        this.addNotification('error', '获取数据失败', '无法从服务器获取翻译数据');
      }
    },
    // 保存翻译到服务器
    async saveTranslation(item) {
      try {
        const params = {
          file_id: item.file_id,
          gossip_id: item.gossip_id,
          content: '[' + item.chinese + ']',//提交时检查并补回中括号
          remark: item.remark
        }
        // 模拟API调用，实际项目中应替换为真实的API端点
        const response = await apiService.translation(params);
        if (response.success) {
          item.translate_prev = item.chinese;//用于保存按钮的禁用启用
          this.addNotification('success', '保存成功');
        }
      } catch (error) {
        console.error('保存翻译失败:', error);
        this.addNotification('error', '保存失败', `无法保存: ${params}`);
      }
    },

    //搜索关键词
    doSearch() {
      this.pagination.page = 1;
      this.fetchTranslations();
    },
    // 清空搜索
    clearSearch() {
      this.searchQuery = '';
      this.file_id = '';
      this.gossip_id = '';
      this.pagination.page = 1;
      this.fetchTranslations();
    },

    // 处理排序
    handleSort() {
      // 重置到第一页
      this.currentPage = 1;
    },

    // 切换排序顺序
    toggleSortOrder() {
      this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
      this.currentPage = 1;
    },

    // 按字段排序
    sortBy(field) {
      if (this.sortField === field) {
        // 如果点击的是当前排序字段，则切换排序顺序
        this.toggleSortOrder();
      } else {
        // 如果点击的是其他字段，则按该字段升序排序
        this.sortField = field;
        this.sortOrder = 'asc';
        this.currentPage = 1;
      }
      this.fetchTranslations();
    },

    // 上一页
    prevPage() {
      this.pagination.page--
      this.fetchTranslations();
    },

    // 下一页
    nextPage() {
      this.pagination.page++
      this.fetchTranslations();
    },


    // 添加通知
    addNotification(type, title, message) {
      const id = this.notificationId++;
      const notification = {
        id,
        type,
        title,
        message,
        progress: 0
      };

      this.notifications.push(notification);

      // 开始进度条动画
      const interval = setInterval(() => {
        if (notification.progress < 100) {
          notification.progress += 2;
        } else {
          clearInterval(interval);
          // 进度完成后移除通知
          this.removeNotification(id);
        }
      }, 30);

      // 5秒后自动移除通知
      setTimeout(() => {
        this.removeNotification(id);
      }, 5000);
    },

    // 移除通知
    removeNotification(id) {
      const index = this.notifications.findIndex(n => n.id === id);
      if (index !== -1) {
        this.notifications.splice(index, 1);
      }
    },
    adjustTextareaHeight(event) {
      const textarea = event.target;
      textarea.style.height = 'auto';
      textarea.style.height = textarea.scrollHeight + 'px';
    },
    async ask_ai(item) {
      if (item.translation == '' || item.translation == undefined) {
        const apiClient = new CozeAPI({
          token: '',
          baseURL: 'https://api.coze.cn',
          allowPersonalAccessTokenInBrowser: true 
        });
        const res = await apiClient.workflows.runs.create({
          workflow_id: '',
          parameters: {
            "input": item.content
          },
        });
        console.log(res.data);
        let result = JSON.parse(res.data.replaceAll("\\n", '\\\\n'));
        item.chinese = result.output;

        // let sample = "{\"output\":\"近战猎鹰攻击：命中时：你还会以正向治疗的方式回复你总生命值的15%。\\n\\n治疗增幅对该治疗效果有效，但法术强度无效。 \"}";
        // let result = JSON.parse(sample.replaceAll("\\n", '\\\\n'));
        // item.chinese = result.output;
      }      
    }
  },
  
  watch: {
    selectedCategory() {
      // 分类改变时重置分页
      this.pagination.page = 1;
    },
  },
  mounted() {
    const currentUser = this.getCurrentUserInfo();
    if (!currentUser || !currentUser.user_id) {
      console.warn('未找到当前登录用户信息');
      return null;
    }
    this.categories.forEach(item => {
      if (currentUser.user_id == item.uid) {
        this.allowCopy = true;
        return;
      }
    });
    // 组件挂载时获取数据
    this.fetchTranslations();
  }
}